package com.esteel.coroutine

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import com.esteel.coroutine.model.ArticalBean
import com.esteel.coroutine.net.RetrofitManager
import com.esteel.executeRequest
import kotlinx.android.synthetic.main.activity_net_request.*
import kotlinx.coroutines.Job
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.Retrofit


/**
 * kotlin协程网络请求
 */
class NetRequestActivity : AppCompatActivity() {


    var loadDataJob: Job? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_net_request)



        btn_request_net.setOnClickListener {
            loadDataJob?.cancel()

            loadDataJob=loadData()
        }
    }

    /**
     * 加载网络数据
     */
    private fun loadData(): Job = executeRequest<ArticalBean>(request = {
        RetrofitManager.getArtical()
    }, onSuccess = {
        val info = it.data.map {
            data ->
              data.name
        }.filter { name ->
            name != ""
        }.toString()
        tv_content.text = info
    }, onFail = {
        it.printStackTrace()
    })

    override fun onDestroy() {
        super.onDestroy()
        loadDataJob?.cancel()  // 取消加载任务
    }
}
